package com.weixin.engine.models.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.googlecode.aviator.AviatorEvaluator;
import com.weixin.common.dto.EmployeeProjectDTO;
import com.weixin.engine.models.mapper.AviatorExpressionMapper;
import com.weixin.engine.models.pojo.AviatorExpression;
import com.weixin.engine.models.pojo.EmployeeProject;
import com.weixin.engine.models.service.IAviatorExpressionService;
import com.weixin.engine.models.service.IEmployeeProjectService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wangchunhui
 * @since 2023-12-362 16:28:38
 */
@Service
@RequiredArgsConstructor
public class AviatorExpressionServiceImpl extends ServiceImpl<AviatorExpressionMapper, AviatorExpression> implements IAviatorExpressionService {


    private final IEmployeeProjectService employeeProjectService;

    @Override
    public List<EmployeeProjectDTO> calculatePerformance() {
        //员工项目完成项目情况列表
        List<EmployeeProject> employeeProjectList = employeeProjectService.list();

        List<EmployeeProjectDTO> employeeProjectDTOList = JSONObject.parseArray(JSONObject.toJSONString(employeeProjectList), EmployeeProjectDTO.class);

        //计算绩效公式
        AviatorExpression performanceExp = this.getOne(Wrappers.lambdaQuery(AviatorExpression.class)
                .eq(AviatorExpression::getVarName, "团队积分计算"));
        //绩效子项计算
        AviatorExpression performanceChildExp = this.getOne(Wrappers.lambdaQuery(AviatorExpression.class)
                .eq(AviatorExpression::getVarName, "计算团队积分子项"));
        for (EmployeeProjectDTO employeeProjectDTO : employeeProjectDTOList) {
            //利用int向下取整的特性去除整数最后一位
            int totalInt = employeeProjectDTO.getTotal() / 10;
            Map<String, Object> map = new HashMap<>();
            map.put("totalInt", totalInt);
            //计算绩效子项
            Double num = (Double) AviatorEvaluator.execute(performanceChildExp.getExpression(), map);
            //计算绩效，并保留一位小数
            Map<String, Object> paramMap = BeanUtil.beanToMap(employeeProjectDTO);
            paramMap.put("num", num);
            Double doublePerformance = (Double) AviatorEvaluator.execute(performanceExp.getExpression(), paramMap);
            employeeProjectDTO.setNum(num);
            employeeProjectDTO.setDoublePerformance(doublePerformance);
        }
        return employeeProjectDTOList;
    }
}
